<?php

namespace app\admin\model;

class User extends Common
{

    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'update_time' => 'timestamp:Y-m-d',
    ];

    /**
     * 用户状态转换为中文
     * @return string
     */
    public function getStatusTextAttr()
    {
        $status = [
            '1' => '正常',
            '2' => '锁定',
            '3' => '禁用',
        ];
        return $status[$this->status];
    }

    /**
     * 获取登录用户信息
     * @param $account
     * @param $password
     * @return null|static
     */
    public function getAdminByLogin($account, $password)
    {
        return $this->get([
            'account'  => $account,
            'password' => $password,
            'status'   => 1,
            'delete'   => 0
        ]);
    }

    /**
     * 重新设置密码
     * @param $uid
     * @param $password
     * @return User|false
     */
    public function changePassword($uid, $password)
    {
        if (!$uid) {
            $this->error = '参数错误';
            return false;
        }
        $_password = thinkEncrypt($password);
        return $this->where('id', $uid)->update(['password' => $_password]);
    }

    /**
     * 检查用户名是否存在
     * @param $where
     * @return null|static
     */
    public function getAdminByUsername($where)
    {
        return $this->get($where);
    }

    /**
     * 获取管理员列表
     * @param $where @查询条件
     * @param $page @分页数据
     * @return \think\Paginator
     */
    public function getAdminList($where = [], $page = 15)
    {
        $data = $this->where($where)->where('delete', 0)->paginate($page);
        foreach ($data as $k => $v) {
            $role = model('JurisdictionGroup')->get(['id' => $v->AdminJurisdiction->jurisdiction_group_id]);
            $data[$k]['role_name'] = $role->data['name'];
        }
        return $data;
    }


    public function companyStaff()
    {
        return $this->hasMany('staff', 'uid')->join('company', 'company.id=staff.company_id');
    }

    /**
     *
     * @return \think\model\relation\BelongsToMany
     */
    public function departments()
    {
        return $this->belongsToMany(Department, "staff", "uid");
    }


}
